/*
 * @Author: linxun 
 * @Date: 2021-03-03 16:28:48 
 * @Last Modified by: linxun
 * @Last Modified time: 2021-07-27 10:33:10
 * @Description: 新增数据集，数据集新增版本(暂时不用)
 */

import React, { useEffect, useState, useRef, Fragment } from 'react';
import { PageHeaderWrapper } from '@ant-design/pro-layout';
import { PageHeader, Modal, Steps, Button, Card, message, Form, Radio } from 'antd';
import { history, useIntl, Prompt, connect } from 'umi';
import {
  fetchDataSetDetail,
  getDataSetFormat,
  createDataSet,
  updateDataSetPathByUplaod,
  updateDataSetPath,
  delDataSet,
  updateDataSetByCondition,
  updateDataSetByKeys
} from './service';
import { FORMLAYOUT_1 } from '@/utils/const';
import FirstStep from './components/FirstStep';
import SecondStep from './components/SecondStep';
import { addonBeforePath } from './components/SecondStep';

import styles from './Add.less';

const { Step } = Steps;
const FormItem = Form.Item;
const RadioGroup = Radio.Group;
const RadioButton = Radio.Button;
let canLeave = true;

const Add = props => {
  const { formatMessage } = useIntl();
  const dataSetId = ~~props.match.params.id;
  const { dataSet: { labelTypes, labelScenes, createSourceType }, dispatch, location: { pathname } } = props;
  const isPublic = pathname?.includes('public');
  const [form] = Form.useForm();
  const [curStep, setCurStep] = useState(0);
  const [loading, setLoading] = useState({
    detail: false,
    first: false,
    submit: false,
  });
  const [dataSetDetail, setDataSetDetail] = useState({});
  const [submitDisabled, setSubmitDisabled] = useState(false);
  const [curDataSetId, setCurDataSetId] = useState(undefined);
  const secondRef = useRef();

  /** 离开当前页面 start */
  const leaveCurPage = location => {
    if (!canLeave && !location.pathname.includes('/dataSet/add')) {
      Modal.confirm({
        title: formatMessage({ id: 'dataSet.dataSet.edit.prompt.title' }),
        content: formatMessage({ id: 'dataSet.dataSet.edit.prompt.content' }),
        okText: formatMessage({ id: 'dataSet.dataSet.edit.prompt.okText' }),
        cancelText: formatMessage({ id: 'dataSet.dataSet.edit.prompt.cancelText' }),
        onOk: async () => {
          if (curDataSetId) {
            const res = await delDataSet({ id: curDataSetId });
            if (res && res.code === 0) {
              setCurDataSetId(undefined);
              canLeave = true;
              history.push(location.pathname);
            }
          } else {
            canLeave = true;
            history.push(location.pathname);
          }
        },
      });
      return false;
    }
    return true;
  };

  const beforeunload = (e) => {
    (e || window.event).returnValue = true;
    return true;
  };
  /** 离开当前页面 end */

  const STEPS_CONFIG = [{
    title: formatMessage({ id: 'dataSet.dataSet.edit.steps.first.title' }),
    key: 1,
    content: (
      <Form form={form} {...FORMLAYOUT_1} scrollToFirstError>
        <FirstStep labelTypes={labelTypes} labelScenes={labelScenes} dataSetId={dataSetId} />
      </Form>
    ),
  }, {
    title: formatMessage({ id: 'dataSet.dataSet.edit.steps.second.title' }),
    key: 2,
    content: (
      <SecondStep setDisabled={setSubmitDisabled} ref={secondRef} isPublic={isPublic} createSourceType={createSourceType} />
    ),
  }];

  const getDataSetDetail = async () => {
    setLoading({ ...loading, detail: true });
    try {
      const res = await fetchDataSetDetail({ id: dataSetId });
      setLoading({ ...loading, detail: false });
      if (res.code === 0) {
        const detail = res.data;
        setDataSetDetail(detail);
        form.setFieldsValue({
          name: detail.name,
          description: detail.description,
          annotScene: detail.annotScene,
          annotType: detail.annotType,
        });
      }
    } catch (err) {
      console.log(err);
    }
  };

  useEffect(() => {
    if (!labelTypes.length) {
      dispatch({ type: 'dataSet/getLabelType' });
    }
    if (!labelScenes.length) {
      dispatch({ type: 'dataSet/getLabelScenes' });
    }
    if (!createSourceType.length) {
      dispatch({ type: 'dataSet/getCreateSourceType' });
    }
    if (dataSetId) {
      getDataSetDetail();
    }

    window.addEventListener('beforeunload', beforeunload);
    return () => {
      // 销毁拦截判断是否离开当前页面
      window.removeEventListener('beforeunload', beforeunload);
    }
  }, []);

  const onFirstClick = () => {
    form.validateFields().then(async values => {
      setLoading({ ...loading, first: true });
      const dataSetFormatRes = await getDataSetFormat({
        cvDatasetType: values.annotType,
      });
      if (dataSetFormatRes && dataSetFormatRes.code === 0) {
        const res = await createDataSet({
          ...values,
          cvDatasetFormat: dataSetFormatRes.data,
        });
        setLoading({ ...loading, first: false });
        if (res && res.code === 0) {
          canLeave = false;
          setCurDataSetId(res.data.id);
          setCurStep(curStep + 1);
        } else {
          setLoading({ ...loading, first: false });
        }
      } else {
        setLoading({ ...loading, first: false });
      }
    }).catch(err => {
      console.log(err);
    });
  };

  const onPreveClick = async () => {
    if (curDataSetId) {
      const res = await delDataSet({ id: curDataSetId });
      if (res && res.code === 0) {
        setCurDataSetId(undefined);
        setCurStep(curStep - 1);
      }
    } else {
      setCurStep(curStep - 1);
    }
  };

  const onSubmit = () => {
    const { rowDataRef, secondForm } = secondRef.current;
    secondForm.validateFields().then(async values => {
      setLoading({ ...loading, submit: true });
      const { sourceType, storagePath, fileList, withAnnotFile } = values;
      if (sourceType === 'make_from_files') {
        // 原始数据导入
        const { selectWay } = values;
        const { searchParams, selectKeys } = rowDataRef.current;
        let params = {
          cvDatasetId: curDataSetId,
          sourceType,
        };
        if (selectWay === 1) {
          // if (JSON.stringify(searchParams) === '{}') {
          //   message.warning('请至少输入一个筛选条件！');
          //   return;
          // }
          params = {
            cvDatasetId: curDataSetId,
            sourceType,
            ...searchParams,
          };
        } else {
          if (!selectKeys || !selectKeys.length) {
            message.warning('请至少选择一条数据！');
            return;
          }
          params.fileList = selectKeys;
        }
        const res = selectWay === 1 ? await updateDataSetByCondition(params) : await updateDataSetByKeys(params);
        setLoading({ ...loading, submit: false });
        if (res && res.code === 0) {
          message.success('创建成功');
          canLeave = true;
          history.push(isPublic ? '/public' : '/QIP/dataManage/dataSet');
        }
      } else {
        // 网页上传 平台导入
        const uploadPath = sourceType === 'upload_from_page' ? fileList[0]?.response?.data?.storagePath : undefined;
        const params = {
          id: curDataSetId,
          sourceType,
          withAnnotFile,
          dirPath: uploadPath || addonBeforePath + storagePath,
          fileName: sourceType === 'upload_from_page' ? fileList[0]?.name : undefined,
        };
        const res = sourceType === 'upload_from_page' ? await updateDataSetPathByUplaod(params) : await updateDataSetPath(params);
        setLoading({ ...loading, submit: false });
        if (res && res.code === 0) {
          message.success('创建成功');
          canLeave = true;
          history.push(isPublic ? '/public' : '/QIP/dataManage/dataSet');
        } else if (res.code === 30117) {
          message.error('数据集标注中不能添加图片！');
          if (option === '1') {
            history.replace(`${pathname}?annotType=${annotType}&option=0`);
          }
        }
      }
    }).catch(err => {
      console.log(err);
    });
  };

  return (
    <PageHeaderWrapper title={false}>
      <PageHeader
        ghost={false}
        // onBack={history.goBack}
        onBack={() => history.push(isPublic ? '/public' : '/QIP/dataManage/dataSet')}
        title={formatMessage({ id: 'menu.dataManage.addDataSet' })}
      ></PageHeader>
      <Prompt message={leaveCurPage} />
      <Card className={styles.card} loading={loading.detail}>
        <Steps current={curStep}>
          {STEPS_CONFIG.map(item => (
            <Step key={item.key} title={item.title} />
          ))}
        </Steps>
        <div className={styles.stepsContent}>{STEPS_CONFIG[curStep].content}</div>
        <div className={styles.stepsAction}>
          {curStep < STEPS_CONFIG.length - 1 && (
            <Button type='primary' onClick={onFirstClick} loading={loading.first}>
              {formatMessage({ id: 'dataSet.dataSet.edit.steps.next' })}
            </Button>
          )}
          {curStep > 0 && (
            <Button style={{ margin: '0 8px' }} onClick={onPreveClick}>
              {formatMessage({ id: 'dataSet.dataSet.edit.steps.prev' })}
            </Button>
          )}
          {curStep === STEPS_CONFIG.length - 1 && (
            <Button type='primary' onClick={onSubmit} disabled={submitDisabled}>
              {formatMessage({ id: 'dataSet.dataSet.edit.steps.done' })}
            </Button>
          )}
        </div>
      </Card>
    </PageHeaderWrapper>
  )
}

export default connect(({ oldDataSet }) => ({
  dataSet: oldDataSet,
}))(Add);